package com.ruoyi.web.controller.clothing;

import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.clothing.domain.vo.ImproveUser;
import com.ruoyi.clothing.domain.vo.Login;
import com.ruoyi.clothing.domain.vo.RegisterUser;
import com.ruoyi.clothing.domain.vo.UpdateData;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.clothing.domain.User;
import com.ruoyi.clothing.service.IUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户管理Controller
 *
 * @author weh
 * @date 2024-01-18
 */
@RestController
@RequestMapping("/clothing/user")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    /**
     * 查询用户管理列表
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出用户管理列表
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户管理数据");
    }

    /**
     * 获取用户管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(userService.selectUserById(id));
    }

    /**
     * 新增用户管理
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user)
    {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户管理
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户管理
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }


    /**
     * app端登陆
     *
     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:login')")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User data) {
        System.out.println("我来了");
        User user = userService.verifyUser(data.getUsername(), data.getPassword());
        //将登陆的用户名存到session中，方便后续的调用判断
//        httpSession.setAttribute("username",username);

        if (user != null) {
            System.out.println("进来了");
            return AjaxResult.success("登录成功", user);
        } else {
            return AjaxResult.error("登录失败，用户名或密码不正确");
        }
    }

    /**
     * pc端登录
     * @param data
     * @return
     */
    @PostMapping("/pclogin")
    public AjaxResult login(@RequestBody Login data) {
        User user = userService.verifyUser(data.getAccount(), data.getPassword());
        if (user != null) {
            System.out.println("用户存在");
            String token = Jwts.builder()
                    .setSubject(data.getAccount())
                    .signWith(SignatureAlgorithm.HS512, secret).compact();
            user.setToken(token);
            return AjaxResult.success("登录成功", user);
        } else {
            return AjaxResult.error("登录失败，用户名或密码不正确");
        }
    }


    /**
     * 注册
     * @param registerUser
     * @return
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterUser registerUser){
        String username = registerUser.getUsername();
        User user = userService.selectUserByUserName(username);
        if (!registerUser.getPassword().equals(registerUser.getConfirmPassword())){
            return AjaxResult.error("两次密码输入不相同，请重新输入");
        }
        else if (user != null){
            return AjaxResult.error("用户已存在，请跳转登录或者重新输入");
        }else {
            userService.register(registerUser);
            return AjaxResult.success("注册成功");
        }
    }


//    /**
//     * 用户注册
//     * @param user
//     * @return
//     */
//    @PreAuthorize("@ss.hasPermi('clothing:user:register')")
//    @PostMapping("/register")
//    public AjaxResult register(@RequestBody User user) {
//        if (userService.selectUserByUserName(user.getUsername()) != null) {
//            return AjaxResult.error("用户已存在，不可添加");
//        } else {
//            return toAjax(userService.insertUser(user));
//        }
//    }
//
//
//    /**
//     * 将业务操作结果转换为AjaxResult
//     */
//    protected AjaxResult toAjax(int rows) {
//        return rows > 0 ? AjaxResult.success("注册成功") : AjaxResult.error("注册失败");
//    }

    /**
     * 修改密码
     * @param updateData
     * @return
     */
//    @PutMapping("/updatePassWord")
//    public AjaxResult updatePassWord(@RequestBody UpdateData updateData) {
//        User user = userService.selectUserByUserName(updateData.getUsername());
//        HashMap<String, Object> map = new HashMap<>();
//        if (!updateData.getNewPassword().equals(updateData.getConfirmPassword())) {
//            return AjaxResult.error("两次密码输入不一样,请重新输入");
//        }
//        if (user == null) {
//            return AjaxResult.error("用户名不存在");
//        } else {
//            map.put("id", user.getId());
//            map.put("newPassword", updateData.getNewPassword());
//            userService.updatePassWord(map);
//            return AjaxResult.success("修改密码成功");
//        }d
//
//    }
    @PutMapping("/updatePassWord")
    public AjaxResult updatePassWord(@RequestBody UpdateData updateData) {
        User user = userService.selectUserByUserName(updateData.getUsername());
        HashMap<String, Object> map = new HashMap<>();
        if (!updateData.getNewPassword().equals(updateData.getConfirmPassword())) {
            return AjaxResult.error("两次密码输入不一样,请重新输入");
        }
        if (user == null) {
            return AjaxResult.error("用户名不存在");
        } else {
            map.put("id", user.getId());
            map.put("newPassword", updateData.getNewPassword());
            userService.updatePassWord(map);
            return AjaxResult.success("修改密码成功");
        }

    }

    /**
     * 完善信息
     * @param data
     * @return
     */
    @PutMapping("/improveUser")
    public AjaxResult improveUser(@RequestBody ImproveUser data){
        userService.improveUser(data);
        return AjaxResult.success("信息完善成功");
    }

    @PutMapping("/improveSex")
    public AjaxResult improveSex(@RequestBody ImproveUser data){
        userService.improveSex(data);
        return AjaxResult.success("修改性别成功");
    }

    @PutMapping("/improveTel")
    public AjaxResult improveTel(@RequestBody ImproveUser data){
        userService.improveTel(data);
        return AjaxResult.success("修改性别成功");
    }

    /**
     * 根据用户名获取id
     * @param username
     * @return
     */
    @GetMapping("/getIdByUsername")
    public Long getIdByUsername(@RequestParam String username){
        User user = userService.selectUserByUserName(username);
        return user.getId();
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @GetMapping("/getUserById")
    public User getUserById(@RequestParam String username){
        User user = userService.selectUserByUserName(username);
        return user;
    }

    @PostMapping("/pcRegister")
    public AjaxResult pcRegister(@RequestBody User user){
        String username = user.getUsername();
        User user1 = userService.selectUserByUserName(username);
        if (user1 != null){
            return AjaxResult.error("用户名已存在，请重新输入或跳转登陆");
        }else {
            userService.insertUser(user);
            return AjaxResult.success("注册成功，请跳转登陆");
        }
    }

}
